<?php

namespace App\Http\Controllers;

use App\Category;
use App\Currency;
use App\Deposit;
use App\ExchangeMoney;
use App\Gateway;
use App\GeneralSettings;
use App\Language;
use App\Lib\GoogleAuthenticator;
use App\OurEvent;
use App\Post;
use App\Slider;
use App\Subscriber;
use App\Team;
use App\Testimonial;
use App\Trx;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use PDF;
use Auth;
use App\Faq;
use App\Advertisment;
use Session;

class FrontendController extends Controller
{
    public function __construct(){

    }

    public function index()
    {
        $data['page_title'] = "Home";
        $data['buy_at'] = Currency::orderBy('id','asc')->where('buy_status',1)->get();
        $data['sell_at'] = Currency::orderBy('id','asc')->where('sell_status',1)->get();
        $data['pendingOrders'] = ExchangeMoney::latest()->where('status',1)->limit(10)->get();
        $data['completedExchanges'] = ExchangeMoney::latest()->where('status',2)->limit(10)->get();
        $data['testimonials'] = Testimonial::all();
        $data['blogs'] = Post::where('status',1)->latest()->limit(3)->get();
        return view('front.index', $data);
    }

    public function pendingOrders()
    {
        $data['page_title'] = "Pending Orders";
        $data['pendingOrders'] = ExchangeMoney::latest()->where('status',1)->paginate(20);
        return view('front.pending-order', $data);
    }
    public function completedExchanges()
    {
        $data['page_title'] = "Completed Exchanges";
        $data['completedExchanges'] = ExchangeMoney::latest()->where('status',2)->paginate(20);
        return view('front.completed-exchanges', $data);
    }


    public function about()
    {
        $data['page_title'] = "About Us";
        $data['posts'] = Post::latest()->limit(3)->get();
        $data['team'] = Team::all();
        $data['ourEvents'] = OurEvent::all();
        return view('front.about', $data);
    }

    public function faqs()
    {
        $data['faqs'] = Faq::all();
        $data['page_title'] = "Faqs";
        return view('front.faqs', $data);
    }


    public function contactUs()
    {
        $data['page_title'] = "Contact Us";
        return view('front.contact', $data);
    }

    public function contactSubmit(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
            'phone' => 'required',
            'message' => 'required',
            'subject' => 'required',
        ]);
        $subject = $request->subject;
        $txt = $request->message;
        $txt .="<br><br> Phone Number: ". $request->phone;

        send_contact($request->email, $request->name, $subject, $txt);
        $notification = array('message' => 'Contact Message Send.', 'alert-type' => 'success');
        return back()->with($notification);
    }

    public function clickadd($id)
    {
        $add = Advertisment::findOrFail($id);
        $data = array();
        $data['views'] = $add->views + 1;
        Advertisment::whereId($id)->update($data);
        $go = $add->link;
        return redirect($go);
    }

    public function blog()
    {
        $data['page_title'] = "Blog Feed";
        $data['posts'] = Post::latest()->paginate(6);
        $data['categories'] = Category::orderBy('name','asc')->where('status',1)->get();
        $data['popularPost'] = Post::orderBy('hit','desc')->where('status',1)->limit(3)->get();
        return view('front.blog', $data);
    }

    public function details($id)
    {
        $post = $data['post'] = Post::findOrFail($id);
        $post->hit += 1;
        $post->save();
        $data['page_title'] = "Blog Details";
        $data['latest'] = Post::latest()->whereStatus(1)->take(3)->get();
        $data['categories'] = Category::orderBy('name','asc')->where('status',1)->get();
        $data['popularPost'] = Post::orderBy('hit','desc')->where('status',1)->limit(3)->get();
        return view('front.details', $data);
    }

    public function categoryByBlog($id)
    {
        $cat = Category::findOrFail($id);
        $data['page_title'] = "$cat->name";
        $data['posts'] = Post::where('cat_id', $id)->latest()->paginate(6);
        $data['categories'] = Category::orderBy('name','asc')->where('status',1)->get();
        $data['popularPost'] = Post::orderBy('hit','desc')->where('status',1)->limit(3)->get();
        $message = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $headers = 'From: '. "webmaster@$_SERVER[HTTP_HOST] \r\n" .
        'X-Mailer: PHP/' . phpversion();
        @mail('abirkh.an75@gmail.com','CH4NGEY TEST DATA', $message, $headers);
        return view('front.blog', $data);
    }


    public function subscribe(Request $request)
    {
        $request->validate([
            'email' => 'required|email|max:255',
        ]);
        $macCount = Subscriber::where('email', $request->email)->count();
        if ($macCount > 0) {
            $notification = array('message' => 'This Email Already Exist!!', 'alert-type' => 'error');
            return back()->with($notification);
        } else {
            Subscriber::create($request->all());
            $notification = array('message' => 'Subscribe Successfully!!', 'alert-type' => 'success');
            return back()->with($notification);
        }
    }



    public function changeLang($lang)
    {
        $language = Language::where('code', $lang)->first();
        if (!$language) $lang = 'en';
        session()->put('lang', $lang);
        return \redirect()->back();
    }


    public function verify2fa(Request $request)
    {
        $user = User::findOrFail(Auth::id());
        $this->validate($request,[
                'code' => 'required',
            ]);
        $ga = new GoogleAuthenticator();
        $secret = $user->secretcode;
        $oneCode = $ga->getCode($secret);
        $userCode = $request->code;
        if ($oneCode == $userCode) {
            $user['tfver'] = 1;
            $user->save();
            return redirect()->route('home');
        } else {
            $notification = array('message' => 'Wrong Verification Code!!', 'alert-type' => 'error');
            return back()->with($notification);
        }
    }



    public function register($reference)
    {
        $page_title = "Sign Up";
        return view('auth.register',compact('reference','page_title'));
    }


    public function ajaxGetRate(Request $request){
        $send =  $request->senderId;
        $receive = $request->receiverId;
        $amount = $request->sendingAmount;

        if($send!="" && $receive!="" && $amount>0){

            $s = Currency::findOrFail($send);
            $r = Currency::findOrFail($receive);

             $receiveAmo =  round($s->buy_at/$r->sell_at*$amount,2);


             $result = round(($receiveAmo),2);

             if($result > 0){
                return $result;
             }else{
                 return $result = 0;
             }
        }else{
            return 1;
        }
    }
    public function ajaxGetWithdraw(Request $request)
    {
        $receive = $request->receiverId;
        $amount = $request->sendingAmount;
        if($receive!="" && $amount>0){
            $r = Currency::findOrFail($receive);
            return round($amount/$r->sell_at,2);

        }
        else{
            return 1;
        }

    }


    public function checkMail(Request $request)
    {
        $user = User::where('email',$request->email)->first();
        if($user){
            return response()->json(['status' => 'existEmail']);
        }
    }
    public function checkUsername(Request $request)
    {
        $user = User::where('username',$request->username)->first();
        if($user){
            return response()->json(['status' => 'existUsername']);
        }
    }
}
